/*
 * Copyright (C) 2011 Patrik Akerfeldt
 * Copyright (C) 2011 Francisco Figueiredo Jr.
 * Copyright (C) 2011 Jake Wharton
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.common.android.ui.viewPagerIndicator;

import java.util.ArrayList;

import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.os.Handler;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.common.android.utils.DisplayUtil;
import com.nd.android.u.allcommon.R;

/**
 * A TitlePageIndicator is a PageIndicator which displays the title of left view
 * (if exist), the title of the current select view (centered) and the title of
 * the right view (if exist). When the user scrolls the ViewPager then titles are
 * also scrolled.
 */
public class TitlePageIndicatorExl extends View implements PageIndicator {
	private static final String NEW_FUNCTION_TAG="CONTACT";
    /**
     * Percentage indicating what percentage of the screen width away from
     * center should the underline be fully faded. A value of 0.25 means that
     * halfway between the center of the screen and an edge.
     */
    private static final float SELECTION_FADE_PERCENTAGE = 0.5f;

    /**
     * Percentage indicating what percentage of the screen width away from
     * center should the selected text bold turn off. A value of 0.05 means
     * that 10% between the center and an edge.
     */
    private static final float BOLD_FADE_PERCENTAGE = 0.5f;
    
    private static final float SEPERATOR_LINE_TOP_MARGIN = 6f;
    private Bitmap mBitmapNew;
    private Handler mHandler;
    private onTabShowNewListener mShowNewListener;
    
    public void setonTabShowNewListener(onTabShowNewListener listener) {
        mShowNewListener = listener;
    }
    
    public void setmHandler(Handler mHandler) {
		this.mHandler = mHandler;
	}

	public enum IndicatorStyle {
        None(0), Triangle(1), Underline(2);

        public final int value;

        private IndicatorStyle(int value) {
            this.value = value;
        }

        public static IndicatorStyle fromValue(int value) {
            for (IndicatorStyle style : IndicatorStyle.values()) {
                if (style.value == value) {
                    return style;
                }
            }
            return null;
        }
    }

    private ViewPager mViewPager;
    private ViewPager.OnPageChangeListener mListener;
    private TitleProvider mTitleProvider;
    private int mCurrentPage;
    private int mCurrentOffsetPixels;
    private int mScrollState;
    private final Paint mPaintText;
    private boolean mBoldText;
    private int mColorText;
    private int mColorSelected;
    private Path mSeperatorPath = new Path();
    private Path mPath = new Path();
    private final Paint mPaintFooterLine;
    private final Paint mPaintSeperatorLine;
    private IndicatorStyle mFooterIndicatorStyle;
    private final Paint mPaintFooterIndicator;
    private float mFooterIndicatorHeight;
    private float mFooterPadding;
    private float mTitlePadding;
    private float mTopPadding;
    /** Left and right side padding for not active view titles. */
    private float mClipPadding;
    private float mFooterLineHeight;
    private float mMarginBottom = 6f;
    public TitlePageIndicatorExl(Context context) {
        this(context, null);
    }

    public TitlePageIndicatorExl(Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.titlePageIndicatorStyle);
    }

    public TitlePageIndicatorExl(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        //Load defaults from resources
        final Resources res = getResources();
        final int defaultFooterIndicatorStyle = res.getInteger(R.integer.default_title_indicator_footer_indicator_style);
        final float defaultFooterIndicatorHeight = res.getDimension(R.dimen.default_title_indicator_footer_indicator_height);
        final float defaultFooterPadding = res.getDimension(R.dimen.default_title_indicator_footer_padding);
        final int defaultSelectedColor = res.getColor(R.color.default_title_indicator_selected_color);
        final boolean defaultSelectedBold = res.getBoolean(R.bool.default_title_indicator_selected_bold);
        final float defaultTitlePadding = res.getDimension(R.dimen.default_title_indicator_title_padding);
        final float defaultTopPadding = res.getDimension(R.dimen.default_title_indicator_top_padding);
        mFooterLineHeight = 5f; //这里设置默认值，不在ondraw中赋值，这样才能让设置函数调用后的值生效，。
        
        //Retrieve styles attributes
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TitlePageIndicator, defStyle, R.style.Widget_TitlePageIndicator);

        //Retrieve the colors to be used for this view and apply them.
        mFooterIndicatorStyle = IndicatorStyle.fromValue(a.getInteger(R.styleable.TitlePageIndicator_footerIndicatorStyle, defaultFooterIndicatorStyle));
        mFooterIndicatorHeight = a.getDimension(R.styleable.TitlePageIndicator_footerIndicatorHeight, defaultFooterIndicatorHeight);
        mFooterPadding = a.getDimension(R.styleable.TitlePageIndicator_footerPadding, defaultFooterPadding);
        mTopPadding = a.getDimension(R.styleable.TitlePageIndicator_topPadding, defaultTopPadding);
        mTitlePadding = a.getDimension(R.styleable.TitleFlowIndicator_titlePadding, defaultTitlePadding);
        mColorSelected = a.getColor(R.styleable.TitleFlowIndicator_selectedColor, defaultSelectedColor);
        mColorText  = Color.rgb(0, 0, 0);
        mBoldText = a.getBoolean(R.styleable.TitlePageIndicator_selectedBold, defaultSelectedBold);

        mPaintText = new Paint();
        mPaintText.setTextSize(DisplayUtil.sp2px(16, context.getResources().getDisplayMetrics().density));
        mPaintText.setAntiAlias(true);
        mPaintFooterLine = new Paint();
        mPaintFooterLine.setStyle(Paint.Style.FILL_AND_STROKE);
        mPaintFooterLine.setStrokeWidth(0);
        mPaintFooterLine.setColor(Color.rgb(0x71, 0xc0, 0x89));
        mPaintFooterIndicator = new Paint();
        mPaintFooterIndicator.setStyle(Paint.Style.FILL_AND_STROKE);
        mPaintFooterIndicator.setStrokeWidth(3);
        mPaintFooterIndicator.setColor(Color.rgb(0x71, 0xc0, 0x89));
        mPaintSeperatorLine = new Paint();
        mPaintSeperatorLine.setStyle(Paint.Style.FILL_AND_STROKE);
        mPaintSeperatorLine.setStrokeWidth(2);
        mPaintSeperatorLine.setColor(Color.rgb(0xe5, 0xe5, 0xe5));
        
        mColorSelected=Color.rgb(0x5e, 0x50, 0x43);
        mColorText=Color.rgb(0x5e, 0x50, 0x43);
        mBitmapNew=BitmapFactory.decodeResource(res, R.drawable.common_icon_new_function);
        a.recycle();
    }
    
    public int getFooterColor() {
        return mPaintFooterLine.getColor();
    }

    /**
     * 设置背景颜色.
     * 
     * Created 2014-9-30 下午5:53:00.
     * @param footerColor
     * @author        :  严鸿贵
     */
    public void setFooterColor(int footerColor) {
        mPaintFooterLine.setColor(footerColor);
        mPaintFooterIndicator.setColor(footerColor);
        invalidate();
    }
    
    public void setFooterSeperatorColor(int footerColor) {
    	mPaintSeperatorLine.setColor(footerColor);
        invalidate();
    }

    public float getFooterLineHeight() {
        return mFooterLineHeight;
    }

    public void setFooterLineHeight(float footerLineHeight) {
        mFooterLineHeight = footerLineHeight;
        mPaintFooterLine.setStrokeWidth(mFooterLineHeight);
        invalidate();
    }

    public float getFooterIndicatorHeight() {
        return mFooterIndicatorHeight;
    }

    public void setFooterIndicatorHeight(float footerTriangleHeight) {
        mFooterIndicatorHeight = footerTriangleHeight;
        invalidate();
    }

    public float getFooterIndicatorPadding() {
        return mFooterPadding;
    }

    public void setFooterIndicatorPadding(float footerIndicatorPadding) {
        mFooterPadding = footerIndicatorPadding;
        invalidate();
    }

    public IndicatorStyle getFooterIndicatorStyle() {
        return mFooterIndicatorStyle;
    }

    public void setFooterIndicatorStyle(IndicatorStyle indicatorStyle) {
        mFooterIndicatorStyle = indicatorStyle;
        invalidate();
    }
    
    public void setFootMarginBottom(float marginBottom){
    	mMarginBottom = marginBottom;
    	invalidate();
    }

    public int getSelectedColor() {
        return mColorSelected;
    }

    
    /**
     * 选中时候字体颜色
     * 
     * Created 2014-9-30 下午6:31:29.
     * @param textColor
     * @author        :  严鸿贵
     */
    public void setSelectedColor(int selectedColor) {
        mColorSelected = selectedColor;
        invalidate();
    }

    public boolean isSelectedBold() {
        return mBoldText;
    }

    public void setSelectedBold(boolean selectedBold) {
        mBoldText = selectedBold;
        invalidate();
    }

    public int getTextColor() {
        return mColorText;
    }

    /**
     * 未选中或者选中时候字体颜色.
     * 
     * Created 2014-9-30 下午5:54:45.
     * @param textColor
     * @author        :  严鸿贵
     */
    public void setTextColor(int textColor) {
        mPaintText.setColor(textColor);
        mColorText = textColor;
        invalidate();
    }

    public float getTextSize() {
        return mPaintText.getTextSize();
    }

    public void setTextSize(float textSize) {
        mPaintText.setTextSize(textSize);
        invalidate();
    }

    public float getTitlePadding() {
        return this.mTitlePadding;
    }

    public void setTitlePadding(float titlePadding) {
        mTitlePadding = titlePadding;
        invalidate();
    }

    public float getTopPadding() {
        return this.mTopPadding;
    }

    public void setTopPadding(float topPadding) {
        mTopPadding = topPadding;
        invalidate();
    }

    public float getClipPadding() {
        return this.mClipPadding;
    }

    public void setClipPadding(float clipPadding) {
        mClipPadding = clipPadding;
        invalidate();
    }

    /*
     * (non-Javadoc)
     *
     * @see android.view.View#onDraw(android.graphics.Canvas)
     */
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        //Calculate views bounds
        ArrayList<RectF> bounds = calculateAllBounds(mPaintText);

        final int count = mViewPager.getAdapter().getCount();
        final float halfWidth = getWidth() / 2f;
        final int left = getLeft();
        final int width = getWidth();
        final int height = getHeight();
        final int right = left + width;
        float cellWidth = width/count;

        int page = mCurrentPage;
        float offsetPercent;
        
        if (mCurrentOffsetPixels <= halfWidth) {
            offsetPercent = 1.0f * mCurrentOffsetPixels / width;
        } else {
            page += 1;
            offsetPercent = 1.0f * (width - mCurrentOffsetPixels) / width;
        }
        final boolean currentSelected = (offsetPercent <= SELECTION_FADE_PERCENTAGE);
        final boolean currentBold = (offsetPercent <= BOLD_FADE_PERCENTAGE);

        //Now draw views
        for (int i = 0; i < count; i++) {
            //Get the title
            RectF bound = bounds.get(i);
            //Only if one side is visible
            if ((bound.left > left && bound.left < right) || (bound.right > left && bound.right < right)) {
                final boolean currentPage = (i == page);
                //Only set bold if we are within bounds
                mPaintText.setFakeBoldText(currentPage && currentBold && mBoldText);

                //Draw text as unselected
                mPaintText.setColor(mColorText);
                canvas.drawText(mTitleProvider.getTitle(i), bound.left, bound.bottom + mTopPadding / 2, mPaintText);

                //点击选中后修改颜色
                if (currentPage && currentSelected) {
                    mPaintText.setColor(mColorSelected);
//                    mPaintText.setFlags(Paint.FAKE_BOLD_TEXT_FLAG);
//                    mPaintText.setAlpha((int)((mColorSelected >>> 24) * selectedPercent));
                      canvas.drawText(mTitleProvider.getTitle(i), bound.left, bound.bottom + mTopPadding / 2, mPaintText);
                }
                
                //画分割线
                if(i != count - 1){
                	mSeperatorPath.moveTo(cellWidth*(i + 1), SEPERATOR_LINE_TOP_MARGIN);
                	mSeperatorPath.lineTo(cellWidth*(i + 1), height - 2 * SEPERATOR_LINE_TOP_MARGIN);
                	mSeperatorPath.close();
                	canvas.drawPath(mSeperatorPath, mPaintSeperatorLine);
                }
                if (mShowNewListener != null) {
                    if (mShowNewListener.showNew(mCurrentPage)) {
                        // 绘制表示新功能的红点
                        int len = (int) mPaintText.measureText(mTitleProvider.getTitle(i));
                        int h = (int) (bound.bottom - bound.top) / 4;
                        canvas.drawBitmap(mBitmapNew, bound.left + len, bound.top + h, mPaintText);
                    }
                }
            }
        }
        final float titleOffset =  mCurrentOffsetPixels/mViewPager.getAdapter().getCount();

        switch (mFooterIndicatorStyle) {
            case Triangle:
                mPath = new Path();
                mFooterIndicatorHeight = 5f;
                mPath.moveTo(cellWidth*(mCurrentPage + 1/2f)+titleOffset, height - mFooterLineHeight - mFooterIndicatorHeight);
                mPath.lineTo(cellWidth*(mCurrentPage + 1/2f)+titleOffset + mFooterIndicatorHeight, height - mFooterLineHeight);
                mPath.lineTo(cellWidth*(mCurrentPage + 1/2f)+titleOffset - mFooterIndicatorHeight, height - mFooterLineHeight);
                mPath.close();
                canvas.drawPath(mPath, mPaintFooterIndicator);
                break;

            case Underline:
                if (!currentSelected) {
                    break;
                }
                
                mPath = new Path();
                mPath.moveTo(cellWidth*mCurrentPage+titleOffset   , height - mMarginBottom );
                mPath.lineTo(cellWidth*(mCurrentPage+1)+titleOffset  , height - mMarginBottom);
                mPath.lineTo(cellWidth*(mCurrentPage+1)+titleOffset  , height  - mFooterIndicatorHeight - mMarginBottom);
                mPath.lineTo(cellWidth*mCurrentPage+titleOffset   , height  - mFooterIndicatorHeight - mMarginBottom);
                mPath.close();

//              mPaintFooterIndicator.setAlpha((int)(0xFF * selectedPercent));
                canvas.drawPath(mPath, mPaintFooterIndicator);
//              mPaintFooterIndicator.setAlpha(0xFF);
                break;
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            final int width = getWidth();
            
            final int cellWidth = width/mViewPager.getAdapter().getCount();
            int selected = (int)(event.getX()/cellWidth);
            if(selected==mSelectedPage){
            	return true;
            }
            else{
            	mViewPager.setCurrentItem(selected);
            	return true;
            }

//            if ((mCurrentPage > 0) && (event.getX() < halfWidth - sixthWidth)) {
//                mViewPager.setCurrentItem(mCurrentPage - 1);
//                return true;
//            } else if ((mCurrentPage < count - 1) && (event.getX() > halfWidth + sixthWidth)) {
//                mViewPager.setCurrentItem(mCurrentPage + 1);
//                return true;
//            }
        }
        return super.onTouchEvent(event);
    }

    /**
     * Set bounds for the right textView including clip padding.
     *
     * @param curViewBound
     *            current bounds.
     * @param curViewWidth
     *            width of the view.
     */
    private void clipViewOnTheRight(RectF curViewBound, float curViewWidth, int right) {
        curViewBound.right = right - mClipPadding;
        curViewBound.left = curViewBound.right - curViewWidth;
    }

    /**
     * Set bounds for the left textView including clip padding.
     *
     * @param curViewBound
     *            current bounds.
     * @param curViewWidth
     *            width of the view.
     */
    private void clipViewOnTheLeft(RectF curViewBound, float curViewWidth, int left) {
        curViewBound.left = left + mClipPadding;
        curViewBound.right = mClipPadding + curViewWidth;
    }

    /**
     * Calculate views bounds and scroll them according to the current index
     *
     * @param paint
     * @param currentIndex
     * @return
     */
//    private ArrayList<RectF> calculateAllBounds(Paint paint) {
//        ArrayList<RectF> list = new ArrayList<RectF>();
//        //For each views (If no values then add a fake one)
//        final int count = mViewPager.getAdapter().getCount();
//        final int width = getWidth();
//        final int halfWidth = width / 2;
//        for (int i = 0; i < count; i++) {
//            RectF bounds = calcBounds(i, paint);
//            float w = (bounds.right - bounds.left);
//            float h = (bounds.bottom - bounds.top);
//            bounds.left = (halfWidth) - (w / 2) - mCurrentOffset + ((i - mCurrentPage) * width);
//            bounds.right = bounds.left + w;
//            bounds.top = 0;
//            bounds.bottom = h;
//            list.add(bounds);
//        }
//
//        return list;
//    }
    
    private int mSelectedPage = 0; 
    private ArrayList<RectF> calculateAllBounds(Paint paint) {
        ArrayList<RectF> list = new ArrayList<RectF>();
        //For each views (If no values then add a fake one)
        final int count = mViewPager.getAdapter().getCount();
        final int width = getWidth();
        if(count==0) return list;
       
        float cellWidth = width/count;
        float half = cellWidth/2;
        //others
        for (int i = 0; i < count; i++) {
        	RectF bounds = calcBounds(i, paint);
//    		bounds.left = getRight()+getWidth();
//    		bounds.right = bounds.left;
        	
        	bounds.left = cellWidth*i+half-bounds.right/2;
        	bounds.right = cellWidth*i+half+bounds.right/2;
        	
    		list.add(bounds);
        }
        return list;
    }

    /**
     * Calculate the bounds for a view's title
     * @param index
     * @param paint
     * @return
     */
    private RectF calcBounds(int index, Paint paint){
        //Calculate the text bounds
        RectF bounds = new RectF();
        bounds.right = paint.measureText(mTitleProvider.getTitle(index));
        bounds.bottom = paint.descent() - paint.ascent();
        return bounds;
    }

    @Override
    public void setViewPager(ViewPager view) {
        if (view.getAdapter() == null) {
            throw new IllegalStateException("ViewPager does not have adapter instance.");
        }
        if (!(view.getAdapter() instanceof TitleProvider)) {
            throw new IllegalStateException("ViewPager adapter must implement TitleProvider to be used with TitlePageIndicator.");
        }
        mViewPager = view;
        mViewPager.setOnPageChangeListener(this);
        mTitleProvider = (TitleProvider)mViewPager.getAdapter();
        invalidate();
    }

    @Override
    public void setViewPager(ViewPager view, int initialPosition) {
        setViewPager(view);
        setCurrentItem(initialPosition);
    }

    @Override
    public void setCurrentItem(int item) {
        if (mViewPager == null) {
            throw new IllegalStateException("ViewPager has not been bound.");
        }
        mViewPager.setCurrentItem(item);
        mCurrentPage = item;
        invalidate();
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        mScrollState = state;
        if (mListener != null) {
            mListener.onPageScrollStateChanged(state);
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        mCurrentPage = position;
        mCurrentOffsetPixels = positionOffsetPixels;
        invalidate();

        if (mListener != null) {
            mListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
        }
    }

    @Override
    public void onPageSelected(int position) {
        if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
            mCurrentPage = position;
            invalidate();
        }
        if(mHandler!=null){
        	mHandler.sendEmptyMessage(position);
        }

        mSelectedPage = position;
        
        if (mListener != null) {
            mListener.onPageSelected(position);
        }
    }

    @Override
    public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
        mListener = listener;
    }

    /*
     * (non-Javadoc)
     *
     * @see android.view.View#onMeasure(int, int)
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec));
    }

    /**
     * Determines the width of this view
     *
     * @param measureSpec
     *            A measureSpec packed into an int
     * @return The width of the view, honoring constraints from measureSpec
     */
    private int measureWidth(int measureSpec) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode != MeasureSpec.EXACTLY) {
            throw new IllegalStateException(getClass().getSimpleName() + " can only be used in EXACTLY mode.");
        }
        result = specSize;
        return result;
    }

    /**
     * Determines the height of this view
     * @param measureSpec
     *            A measureSpec packed into an int
     * @return The height of the view, honoring constraints from measureSpec
     */
    private int measureHeight(int measureSpec) {
        float result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode == MeasureSpec.EXACTLY) {
            //We were told how big to be
            result = specSize;
        } else {
            //Calculate the text bounds
            RectF bounds = new RectF();
            bounds.bottom = mPaintText.descent()-mPaintText.ascent();
            result = bounds.bottom - bounds.top + mFooterLineHeight + mFooterPadding + mTopPadding;
            if (mFooterIndicatorStyle != IndicatorStyle.None) {
                result += mFooterIndicatorHeight;
            }
        }
        return (int)result;
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        SavedState savedState = (SavedState)state;
        super.onRestoreInstanceState(savedState.getSuperState());
        mCurrentPage = savedState.currentPage;
        requestLayout();
    }

    @Override
    public Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        SavedState savedState = new SavedState(superState);
        savedState.currentPage = mCurrentPage;
        return savedState;
    }

    static class SavedState extends BaseSavedState {
        int currentPage;

        public SavedState(Parcelable superState) {
            super(superState);
        }

        private SavedState(Parcel in) {
            super(in);
            currentPage = in.readInt();
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            super.writeToParcel(dest, flags);
            dest.writeInt(currentPage);
        }

        public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
            @Override
            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in);
            }

            @Override
            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }
        };
    }
    
    /**
     * 判断是否要显示红点.
     * 
     * Created 2014-9-30 下午5:40:56.
     * @version  TitlePageIndicatorExl
     * @author   严鸿贵		
     *
     * @see
     */
    public interface onTabShowNewListener {
        boolean showNew(int currentPage);
    }
}
